<template>
	<view class="container">
		<view class="top">
			<view class="select">
				<uni-data-select v-model="value" :localdata="range" @change="change"></uni-data-select>
			</view>

			<uni-icons @click="addCategory" type="plus" size="20"></uni-icons>

		</view>
		<view class="page-body">
			<view class='wrapper'>
				<view class='toolbar' @tap="format" style="height: 80px;overflow-y: auto;">
					<view :class="formats.bold ? 'ql-active' : ''" class="iconfont icon-zitijiacu" data-name="bold">
					</view>
					<view :class="formats.italic ? 'ql-active' : ''" class="iconfont icon-zitixieti" data-name="italic">
					</view>
					<view :class="formats.underline ? 'ql-active' : ''" class="iconfont icon-zitixiahuaxian"
						data-name="underline"></view>
					<view :class="formats.align === 'center' ? 'ql-active' : ''" class="iconfont icon-juzhongduiqi"
						data-name="align" data-value="center"></view>
					<view :class="formats.align === 'right' ? 'ql-active' : ''" class="iconfont icon-youduiqi"
						data-name="align" data-value="right"></view>
					<view :class="formats.align === 'justify' ? 'ql-active' : ''" class="iconfont icon-zuoyouduiqi"
						data-name="align" data-value="justify"></view>

					<view class="iconfont icon-date" @tap="insertDate"></view>
					<view class="iconfont icon--checklist" data-name="list" data-value="check"></view>
					<view :class="formats.list === 'ordered' ? 'ql-active' : ''" class="iconfont icon-youxupailie"
						data-name="list" data-value="ordered"></view>
					<view :class="formats.list === 'bullet' ? 'ql-active' : ''" class="iconfont icon-wuxupailie"
						data-name="list" data-value="bullet"></view>

					<view class="iconfont icon-undo" @tap="undo"></view>
					<view class="iconfont icon-redo" @tap="redo"></view>

					<view class="iconfont icon-outdent" data-name="indent" data-value="-1"></view>
					<view class="iconfont icon-indent" data-name="indent" data-value="+1"></view>
					<view class="iconfont icon-fengexian" @tap="insertDivider"></view>
					<view class="iconfont icon-charutupian" @tap="insertImage"></view>
					<view class="iconfont icon-shanchu" @tap="clear"></view>
				</view>

				<view class="editor-wrapper">
					<editor id="editor" class="ql-container" show-img-size show-img-toolbar show-img-resize
						@statuschange="onStatusChange" :read-only="readOnly" @ready="onEditorReady">
					</editor>

				</view>
				<button @click="chooseFiles">选择文件</button>
				<!-- image/video/all	选择文件类型,all 只支持 H5 和微信小程序平台 -->
				<!-- <uni-file-picker v-model="files" fileMediatype="all" mode="grid" @select="select" @progress="progress"
					@success="success" @fail="fail" /> -->

			</view>
		</view>


		<view class="save-btn " @click="submitContent">
			<text class="save-btn-text">保存 </text>
		</view>
		<uni-popup ref="popUpRemarkRef" type="dialog">
			<uni-popup-dialog ref="inputClose" mode="input" title="新增分类" value="对话框预置提示内容!"
				@confirm="dialogInputConfirm"></uni-popup-dialog>
		</uni-popup>


	</view>

</template>

<script lang="ts" setup>
	import { nextTick, onMounted, ref } from 'vue'
	import { onLoad, onUnload } from '@dcloudio/uni-app'
	import { userStore } from '@/store/user'
	import { notesApi, noteCategoriesApi, universalApi } from "@/apis/apis"

	const SysUser = JSON.parse(uni.getStorageSync('SysUser') || '{}')

	// 初始化请求分类
	const getCategory = async () => {
		const res : any = await noteCategoriesApi.queryPageUsingPOST_7({ userId: SysUser.id })

		userStore.setNoteCategory(res.data.records)
		setRange()

	}

	// 填写备注
	const popUpRemarkRef = ref(null)
	const dialogInputConfirm = async (val : string) => {
		let res : any = await noteCategoriesApi.addUsingPOST_7({
			categoryName: val,

		})
		if (res.code === 200) {
			uni.showToast({ title: res.msg, icon: 'success' })
			popUpRemarkRef.value.close()
			getCategory()
		}
	}

	// 1.editor
	const editorCtx : any = ref('')
	const readOnly = ref(false)
	const formats : any = ref({})
	console.log(userStore.CurrentBook);
	const form = ref({
		"accountBookId": userStore.CurrentBook?.id,
		accountBookName: userStore.CurrentBook?.name,
		"content": "",
		"createTime": "",
		"id": "",
		"noteCategoryId": "",
		"title": "",
		"updateTime": "",
		type: '0',//是否来自缓存(1:是 0:否) 
		"userId": SysUser.id,
		notesFList: []
	})

	const pageType = ref('add')

	const value = ref(0)

	const range = ref([])

	const change = (e : any) => {
		console.log("e:", e);
	}
	const setRange = () => {
		userStore.NoteCategory?.forEach((item : { categoryName : string }, i : number) => {
			range.value.push(
				{ value: i, text: item.categoryName }
			)
		})
	}


	onLoad((options : any) => {
		pageType.value = options.pageType
		setRange()

		form.value.noteCategoryId = userStore.NoteCategory[0].id

		if (options.pageType === 'edit') {
			// 逐个属性更新保持响应式
			Object.keys(form.value).forEach(key => {
				if (userStore.CurrentNote[key] !== undefined) {
					form.value[key] = userStore.CurrentNote[key];
				}
			});

		} else {

			getTempAdd()
		}
	})
	onMounted(() => {
		nextTick(() => {
			const setC = setInterval(() => {
				if (editorCtx.value) {
					editorCtx.value.setContents({
						html: form.value.content
						, success: () => console.log('初始化临时数据')
					})

					clearInterval(setC)
				}
			})

		})
	})
	const addCategory = () => {
		popUpRemarkRef.value.open()
	}

	const getTempAdd = async () => {

		const res : any = await notesApi.queryTemporaryUsingGET({
			userId: SysUser.id
		})
		if (res.code === 200 && res.data.notesTemporary.accountBookId && res.data.notesTemporary.accountBookId !== "undefined") {
			form.value.content = res.data.notesTemporary.content
			form.value.userId = res.data.notesTemporary.userId
			form.value.noteCategoryId = res.data.notesTemporary.noteCategoryId
			form.value.accountBookId = res.data.notesTemporary.accountBookId
			form.value.type = '1'

			userStore.NoteCategory.find((item, idx) => {
				if (item.id === form.value.noteCategoryId) {
					value.value = idx
					return true
				}
			})

			editorCtx.value.setContents({
				html: form.value.content
				, success: () => console.log('初始化临时数据')
			})
		}
	}

	const onEditorReady = () => {
		uni.createSelectorQuery().select('#editor').context((res : any) => {
			editorCtx.value = res.context
		}).exec()
	}
	const undo = () => {
		editorCtx.value.undo()
	}
	const redo = () => {
		editorCtx.value.redo()
	}
	const format = (e : any) => {
		let {
			name,
			value
		} = e.target.dataset
		if (!name) return
		editorCtx.value.format(name, value)
	}
	const onStatusChange = (e) => {

		formats.value = e.detail
	}
	const insertDivider = () => {
		editorCtx.value.insertDivider({
			success: function () {
				console.log('insert divider success')
			}
		})
	}
	const clear = () => {
		uni.showModal({
			title: '清空编辑器',
			content: '确定清空编辑器全部内容？',
			success: res => {
				if (res.confirm) {
					editorCtx.value.clear({
						success: function (res) {
							console.log("clear success")
						}
					})
				}
			}
		})
	}


	const removeFormat = () => {
		editorCtx.value.removeFormat()
	}
	const insertDate = () => {
		const date = new Date()
		const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
		editorCtx.value.insertText({
			text: formatDate
		})
	}
	const chooseImage = () => uni.chooseImage({
		sourceType: ['camera', 'album'],
		count: 1,
		success: async (res) => {

			const path = res.tempFilePaths[0]

			const fileImg : any = await universalApi.uploadUsingPOST({}, path)

			form.value.notesFList.push({
				fileUrl: fileImg
			})

			editorCtx.value.insertImage({
				src: 'http://192.168.3.200:8082/universal/img/' + fileImg,
				alt: '图像',
				success: function () {
					console.log('insert image success')
				}
			})

		}
	})


	const insertImage = async () => {
		// accredit()
		chooseImage()
	}

	const autoSave = setInterval(async () => {
		editorCtx.value.getContents({
			success: async (res : any) => {
				// console.log('带附件的内容:', res.html);

				const add : any = await notesApi.addTemporaryUsingPOST({
					...form.value,
					content: res.html
				})
				if (add.code === 200) {
					console.log('临时新增成功');
				}

			}
		});

	}, 5000)
	onUnload(() => {
		clearInterval(autoSave)
	})
	// 提交内容
	const submitContent = () => {
		console.log(editorCtx.value);
		editorCtx.value.getContents({
			success: (res : any) => {
				console.log('带附件的内容:', res.html);
				submit(res)
			}
		});
	}

	const downFiles = (fileUrl : string) => {
		// 下载文件
		uni.downloadFile({
			url: fileUrl,
			success: res => {
				if (res.statusCode === 200) {
					// 打开文件（支持PDF/Word/Excel等）
					uni.openDocument({
						filePath: res.tempFilePath,
						showMenu: true,
						success: () => console.log('打开成功')
					});
				}
			}
		});
	}



	const submit = async (res : any) => {
		const res2 : any = await notesApi[pageType.value === 'add' ? 'addUsingPOST_8' : 'updateUsingPUT_5']({
			// const res2 : any = await notesApi.addUsingPOST_8({
			...form.value,
			content: res.html
		})
		console.log(res2);

		if (res2.code === 200) {
			uni.showToast({ title: res2.msg, icon: 'success' });
			uni.navigateBack()

		}
	}

	const files = ref('')
	const chooseFiles = () => {
		console.log(11111);
		// #ifdef APP-PLUS
		try {

			plus.android.requestPermissions(
				['android.permission.WRITE_EXTERNAL_STORAGE'],
				(e) => {
					if (e.granted.length > 0) {
						console.log("权限已授权");

					} else if (e.deniedAlways.length > 0) {
						uni.showModal({
							title: "提示",
							content: "权限被永久拒绝，请前往设置中开启",
							showCancel: false
						});
					}
				},
				(err) => { console.log("申请失败", err); }
			);

			const AfDocument = uni.requireNativePlugin("Aq-ChooseFile");
			console.log(11111);
			AfDocument.openMode({
				size: '1', //选择总数量
				paths: ['/storage/emulated/0/Download', '/storage/emulated/0/A',],   //自定义选择目录
				isDown: true,//是否下钻（true 筛选当前目录以下的所有文件，fales 只筛选当前目录文件） 
				types: [{
					name: '文档',
					value: ["doc", "wps", "docx", "xls", "xlsx", "pdf"]
				}, {
					name: '视频',
					value: ["mp4"]
				}, {
					name: '音乐',
					value: ['mp3', 'flac']
				}, {
					name: '图片',
					value: ['jpg', 'png']
				}]
			}, async (e) => {
				console.log(11111);
				/* 
				 {
				 "code": "success",
				 "res": [{
					 name:'文件名',
					 size:'28.4MB',
					 sizeHolp:'29779073',
					 path:'路径',
					 type:'文件类型'
				 }]
				 }*/
				console.log(e);

				try {
					if (e.code === 'success') {
						const path = e.res[0].path

						const fileImg : any = await universalApi.uploadUsingPOST({}, path)
						editorCtx.value.getContents({
							success: (res : any) => {
								console.log(res.html);
								const fileUrl = `192.168.3.200:8082/universal/img/${fileImg}`
								editorCtx.value.setContents({
									html: `${res.html} <a href="${fileUrl}" download="${e.res[0].name}"  style="color:blue;">📎 ${e.res[0].name}</a>`,
									success: () => console.log('文件插入成功')
								})
							}
						})
					}
				} catch (error) {

					console.log(error);
				}
			})

		} catch (error) {
			console.log(error);
		}
		// #endif
		// #ifdef H5
		// 使用 uni.chooseFile API
		uni.chooseFile({
			count: 1,
			type: 'all',
			success: async (e) => {
				const path = e.tempFilePaths[0]

				const fileImg : any = await universalApi.uploadUsingPOST({}, path)
				editorCtx.value.getContents({
					success: (res : any) => {
						console.log(res.html);
						const fileUrl = `192.168.3.200:8082/universal/img/${fileImg}`

						editorCtx.value.setContents({
							html: `${res.html} <a href="${fileUrl}" download="${e.tempFiles[0].name}" style="color:blue;" >📎 ${e.tempFiles[0].name}</a>`,
							success: () => console.log('文件插入成功')
						})
					}
				})
			},
			fail: (err) => {
				console.error('文件选择失败:', err);
			}
		});
		// #endif
	}

	const handleDownload = (fileUrl, fileName) => {

		uni.request({
			url: fileUrl,
			responseType: 'arraybuffer'
		}).then(res => {
			const blob = new Blob([res[1].data]); // 通过返回的流数据 手动构建blob 流

			//方法1
			const a = document.createElement("a");
			//blob:localhost
			a.download = fileName;
			a.href = window.URL.createObjectURL(blob);
			document.body.appendChild(a);
			a.click();
			document.body.removeChild(a);

			//方法2
			// const reader = new FileReader();
			// reader.readAsDataURL(blob); // 转换为base64，可以直接放入a标签的href
			// reader.onload = (e) => {

			// 	// 转换完成，创建一个a标签用于下载
			// 	const a = document.createElement("a");
			// 	a.download = i.fileName;
			// 	a.href = e.target.result;
			// 	document.body.appendChild(a);
			// 	a.click();
			// 	document.body.removeChild(a);
			// }

		})

	}
</script>

<style lang="scss" scoped>
	@import "@/pages/note/editor-icon.css";

	.popup-content {
		width: 200px;

		padding: 15px;
		height: 50px;
		background-color: #fff;
	}

	.popup-height {
		width: 200px;
	}

	.page-body {
		height: calc(100vh - var(--window-top) - var(--status-bar-height));
	}

	.top {
		// width: 100%;
		display: flex;
		// justify-content: space-between;
		align-items: center;
		padding: 10px;

		.select {
			width: 30px;
			width: 40%;
			margin-right: 10px;
		}

	}

	.wrapper {
		height: 100%;
	}

	.editor-wrapper {
		height: calc(100vh - var(--window-top) - var(--status-bar-height) - 280px);
		background: #fff;
	}

	.iconfont {
		display: inline-block;
		padding: 8px 8px;
		width: 24px;
		height: 24px;
		cursor: pointer;
		font-size: 20px;
	}

	.toolbar {
		box-sizing: border-box;
		border-bottom: 0;
		font-family: 'Helvetica Neue', 'Helvetica', 'Arial', sans-serif;
	}

	.ql-container {
		box-sizing: border-box;
		padding: 12px 15px;
		width: 100%;
		min-height: 30vh;
		height: 100%;
		margin-top: 20px;
		font-size: 16px;
		line-height: 1.5;
	}

	.ql-active {
		color: #06c;
	}
</style>


<!-- 
	
	// 申请相机权限示例
	const accredit = () => {
		try {
			// 检查权限状态
			uni.getSetting({
				success: (res) => {
					if (!res.authSetting['scope.camera']) {
						uni.showModal({
							title: '权限未开启',
							content: '需要相机权限才能拍照，是否去设置？',
							success: (res) => {
								if (res.confirm) {
									uni.openSetting(); // 跳转应用设置页
								}
							}
						});
					}
				}
			});
		} catch (error) {
			console.log(error);
		}
	
		try {
			const permissions = ['android.permission.CAMERA'];
			plus.android.requestPermissions(permissions, (e) => {
				if (e.deniedAlways.length > 0) {
					// 权限被永久拒绝：引导用户去设置页开启
					showModalAndOpenSettings('相机');
				} else if (e.deniedPresent.length > 0) {
					// 权限被临时拒绝：可再次申请
					plus.android.requestPermissions(permissions); // 重新申请
				} else {
					// 权限已授予
					console.log("权限获取成功");
				}
			});
		} catch (error) {
			console.log(error);
		}
	
	}
	
	const showModalAndOpenSettings = (permissionName) => {
		try {
			uni.showModal({
				title: '提示',
				content: `请在设置中开启${permissionName}权限`,
				success: (res) => {
					if (res.confirm) {
						const Intent = plus.android.importClass('android.content.Intent');
						const uri = plus.android.importClass('android.net.Uri');
						const intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
						intent.setData(uri.parse('package:' + plus.android.runtimeMainActivity().getPackageName()));
						plus.android.runtimeMainActivity().startActivity(intent);
					}
				}
			});
		} catch (error) {
			console.log(error);
		}
	} 
	
	
	// 选择文件
	const select = async (e) => {
	
		const path = e.tempFilePaths[0]
	
		console.log(path);
		const fileImg : any = await universalApi.uploadUsingPOST({}, path)
		const fileUrl = `192.168.3.200:8082/universal/img/${fileImg}`
		console.log('选择文件：', e)
		editorCtx.value.getContents({
			success: (res) => {
				console.log(res.html);
				editorCtx.value.setContents({
					html: `${res.html}<a href="${fileUrl}"  target="downloadFile" @click="${() => downFiles(fileUrl)}"  download="${e.tempFiles[0].name}" style="color:blue;">📎 ${e.tempFiles[0].name}</a>`,
					success: () => console.log('文件插入成功')
				})
			}
		})
	}
	// 获取上传进度
	const progress = (e) => {
		console.log('上传进度：', e)
	}
	
	// 上传成功
	const success = (e) => {
		console.log('上传成功')
	}
	
	// 上传失败
	const fail = (e) => {
		console.log('上传失败：', e)
	}
	/* // 文件读取为二进制的通用函数
	function readFileToBinary(filePath) {
		return new Promise((resolve, reject) => {
			// 微信小程序	
			// #ifdef MP-WEIXIN
			wx.getFileSystemManager().readFile({
				filePath,
				success: res => resolve(res.data),
				fail: reject
			});
	
			// App 平台
			// #elifdef APP-PLUS
			plus.io.resolveLocalFileSystemURL(filePath, entry => {
				entry.file(file => {
					const reader : any = new plus.io.FileReader();
					reader.onloadend = evt => resolve(evt.target.result);
					reader.readAsArrayBuffer(file);
				}, reject);
			}, reject);
	
			// H5 平台
			// #else
			const xhr = new XMLHttpRequest();
			xhr.open('GET', filePath, true);
			xhr.responseType = 'arraybuffer';
			xhr.onload = () => resolve(xhr.response);
			xhr.onerror = reject;
			xhr.send();
			// #endif
		});
	} */
 
	// 以下代码没使用

	/* 	const fileInputRef = ref(null)
		// 2.自定义上传文件
		// 插入文件（跨平台）
		const insertFile = () => {
	
			fileInputRef.value.click();
	
	
		} */
		
		// 文件上传方法（需替换为实际接口）
		const uploadFile = (filePath : any) => {
			return new Promise((resolve, reject) => {
				uni.uploadFile({
					url: 'https://your-api.com/upload', // 替换为实际接口
					filePath,
					name: 'file',
					success: (res) => {
						const data = JSON.parse(res.data);
						resolve(data.url); // 假设接口返回 {url: 'https://...'}
					},
					fail: reject
				});
			});
		}
		
		
		
	// 插入文件（如PDF、Word等）
	/*const onH5FileChange = async (e) => {
 // 1. 选择文件
	const res:any = uni.chooseMessageFile({
		count: 1,
		type: 'all',
	});
	
	if (!res) return;
	
	// 2. 上传文件到服务器（伪代码）
	uni.showLoading({ title: '上传中...' });
	const fileUrl = await this.uploadFile(res.tempFiles[0].path);
	const fileName = res.tempFiles[0].name;
	uni.hideLoading();
	
	// 3. 插入文件链接到编辑器
	editorCtx.value.insertHTML({
		html: `<a href="${fileUrl}" download="${fileName}" style="color:blue;">📎 ${fileName}</a>`,
		success: () => console.log('文件插入成功')
	}); 
	const file = e.target.files[0];
	if (!file) return;

	// 重置input值，允许重复选择相同文件
	e.target.value = '';

	// H5需要特殊处理文件路径
	const filePath = URL.createObjectURL(file);
	// processFile(filePath.file.name);
} 	const processFile = async (filePath:any) => {
		uni.showLoading({ title: '上传中...' });
	
		try {
			const fileUrl = await uploadFile(filePath);
			this.editorCtx.insertHTML({
				html: `<a href="${fileUrl}" download="${fileName}" style="color:blue;display:inline-block;padding:5px;">📎 ${fileName}</a>`,
				success: () => console.log('文件插入成功')
			});
		} catch (error) {
			console.error('文件上传失败', error);
			uni.showToast({ title: '上传失败', icon: 'none' });
		} finally {
			uni.hideLoading();
		}
	} */ -->